package com.xjc.business.controller.stu;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjc.business.entity.domain.AllStudentRegsiterRelations;
import com.xjc.business.entity.domain.AllStudentStayRelations;
import com.xjc.business.entity.domain.WxUser;
import com.xjc.business.mapper.AllStudentStayRelationsMapper;
import com.xjc.business.service.*;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.properties.WeiXinProperties;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.HttpClientUtil;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 徐锦程
 * 时间:2025-02-03 10:47
 */
@RestController
@RequestMapping("/student/user")
public class StuUserController {

    @Autowired
    WxUserService wxUserService;

    @Autowired
    WeiXinProperties weiXinProperties;

    @Autowired
    HttpClientUtil httpClientUtil;

    @Autowired
    AllStudentStayRelationsService allStudentStayRelationsService;

    @Autowired
    SchoolSetsService schoolSetsService;

    @PostMapping("/login") //微信登录
    public Result<Map<String,Object>> wxLogin(@RequestBody Map<String,String> userInfo){

        String code = userInfo.get("code"); //凭证

        //拼装请求地址
        String url = weiXinProperties.getJscode2sessionUrl()+"?appid="+weiXinProperties.getAppid()+"&secret="+weiXinProperties.getSecret()+"&js_code="+code+"&grant_type=authorization_code";

        //获取openid和session_key
        String result = httpClientUtil.sendHttpGet(url);

        //解析
        JSONObject jsonObject = JSONObject.parseObject(result);

        //openid
        String openid = jsonObject.get("openid").toString();

        //查询数据库判断是否已经存在  不存在则添加
        LambdaQueryWrapper<WxUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WxUser::getWxid,openid);

        WxUser user = wxUserService.getOne(wrapper);
        if(user == null){ //不存在则添加

            user = new WxUser();
            user.setWxid(openid);
            user.setNick("默认昵称");
            user.setPic("/static/default.png");
            user.setStatus(0);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            wxUserService.save(user);
        }


        if (user.getStuId()!=null && !schoolSetsService.sureHasSet(MyConstants.STU_ROLE_LOGIN,user.getStuId())) {
            throw new MyException(ResultCode.NOTOPEANSET.getCode(),ResultCode.NOTOPEANSET.getMessage());
        }

        //生成token 返回token
        String token = TokenUtils.generateToken(user.getId());

        Map<String,Object> map = new HashMap<>();

        map.put("token",token);
        map.put("nickname",user.getNick());
        map.put("avatar",user.getPic());
        map.put("id",user.getId());
        map.put("status",user.getStatus());

        if(user.getStuId() == null){
            map.put("stayStatus",false);

        }else {
            //住宿信息
            LambdaQueryWrapper<AllStudentStayRelations> allStudentStayRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            allStudentStayRelationsLambdaQueryWrapper.eq(AllStudentStayRelations::getStuId, user.getStuId());
            AllStudentStayRelations allStudentStayRelations = allStudentStayRelationsService.getOne(allStudentStayRelationsLambdaQueryWrapper);
            map.put("stayStatus", allStudentStayRelations != null);
        }
        return Result.okWithData(map);
    }
}
